package com.zst.sw.server.module.span;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zst.sw.server.module.segmentref.SegmentRefMapper;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
import org.apache.skywalking.apm.network.language.agent.v3.SpanObject;

import java.util.Collections;
import java.util.List;

public class SpanMapper {
    public static List<Span> map(List<SpanObject> list) {
        if (list == null) {
            return Collections.emptyList();
        }

        List<Span> ret = Lists.newArrayListWithExpectedSize(list.size());
        for (SpanObject spanObject : list) {
            ret.add(map(spanObject));
        }
        return ret;
    }

    public static Span map(SpanObject spanObject) {
        if (spanObject == null) {
            return null;
        }

        Span span = new Span();
        span.setSpanId(spanObject.getSpanId());
        span.setParentSpanId(spanObject.getParentSpanId());
        span.setStartTime(spanObject.getStartTime());
        span.setEndTime(spanObject.getEndTime());
        span.setSpanType(spanObject.getSpanType().getNumber());
        span.setSpanLayer(spanObject.getSpanLayer().getNumber());
        span.setComponentId(spanObject.getComponentId());
        span.setError(spanObject.getIsError());

        if (!spanObject.getTagsList().isEmpty()) {
            span.setTags(Maps.newHashMapWithExpectedSize(spanObject.getTagsList().size()));
            for (KeyStringValuePair tagKv : spanObject.getTagsList()) {
                span.getTags().put(tagKv.getKey(), tagKv.getValue());
            }
        }

        if (!spanObject.getRefsList().isEmpty()) {
            span.setRefs(SegmentRefMapper.map(spanObject.getRefsList()));
        }

        return span;
    }
}
